package com.ddh.bankmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddh.bankmanager.domain.rsa.Rsa;
import com.ddh.bankmanager.mapper.RsaMapper;
import com.ddh.bankmanager.service.RSAService;
import com.ddh.bankmanager.utils.Base64Utils;
import com.ddh.bankmanager.utils.RSAUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import java.beans.Transient;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@Service
@Slf4j
public class RSAServiceImpl extends ServiceImpl<RsaMapper, Rsa>
    implements RSAService {

    /**
     * 公钥加密
     * @param data
     * @return
     */
    @SneakyThrows
    @Override
    public String publicKeyEncryption(String data) {
        Rsa rsa = getOne(new LambdaQueryWrapper<Rsa>().eq(Rsa::getId, 1));
        String publicKey = rsa.getPublicKey();
        String privateKey = rsa.getPrivateKey();
        //公钥加密
        System.out.println("********************公钥加密、生成数字签名、数字签名校验、私钥解密********************");
        System.out.println("字符串：" + data);
        String encryptPublic = Base64Utils.encode(RSAUtils.encryptByPublicKey(data.getBytes(), publicKey));
        System.out.println("公钥加密后字符串：" + encryptPublic);
        //生成数字签名
        String signKey = RSAUtils.sign(Base64Utils.decode(encryptPublic), privateKey);
        System.out.println("公钥加密后数字签名：" + signKey);
        //校验数字签名
        boolean verify = RSAUtils.verify(Base64Utils.decode(encryptPublic), publicKey, signKey);
        System.out.println("公钥加密后数字签名校验：" + verify);
        return encryptPublic;
    }

    /**
     * 私钥解密
     * @param data
     * @return
     */
    @SneakyThrows
    @Override
    public String privateKeyDecrypt(String data) {
        Rsa rsa = getOne(new LambdaQueryWrapper<Rsa>().eq(Rsa::getId, 1));
        String publicKey = rsa.getPublicKey();
        String privateKey = rsa.getPrivateKey();
        String decryptByPrivateKey = new String(RSAUtils.decryptByPrivateKey(Base64Utils.decode(data), privateKey));
        //私钥解密
        System.out.println("私钥解密后字符串：" + decryptByPrivateKey);
        return decryptByPrivateKey;
    }
}
